const { TomatoUrl } = require("../../config/config")
const util = require('../../utils/util.js');
const back = wx.getBackgroundAudioManager();
const times = []
const db = wx.cloud.database()
for (let i = 1; i <= 60; i++) {
  if(i<10){
    times.push('0'+i)
  }else{
    times.push(i)
  }
}
// 在页面中定义插屏广告
let interstitialAd = null
Page({
  data: {
    times:times,
    day: 25,//time
    time:'02',
    mTime:'1500000',
   // timeStr:'25:00',
   timeStr:'02:00',
    pickerValue:[24],//设置picker的默认值为25，防止第一个数拖动时取不到
    clockShow:false,
    clockHeight:0,
    rate:'',
    timer:null,
    pickerShow:false,
    cancleShow:false,
    startShow:true,
    timeLong:25,
    tomatoRecord:{
      uid:'',
      timeLong:'',
    },
    sound:false,
    nickName:'',
    avatarUrl:'',
    isLogin:0,
      //画布--------------------------------
      canvasWidth: 400,
      canvasHeight: 650,
      showCanvasFlag: false,
      
      colorArr: [
        '#EE534F',
        '#FF7F50',
        '#FFC928',
        '#66BB6A',
        '#42A5F6',
        '#5C6BC0',
        '#AA47BC',
        '#EC407A',
        '#FFB6C1',
        '#FFA827'
     ],
     fontArr: ['italic', 'oblique', 'normal'],
     sizeArr: [12, 14, 16, 18, 20, 22, 24, 26, 28],

     eweimaUrl: '../../images/erweima.jpg',

     shengchengUrl: '',
     saveFrameFlag: false,
     awards:[
      '防治便秘', '防止痔疮', '缓解尿失禁', '保护男性前列腺', '提升性功能', '提高夫妻生活质量'
     ],
     miaovalue:1,
     biaoji:0
  },

  
   //关闭保存图片的框
   closeSaveFrame: function () {
    var that = this;

    that.setData({
       saveFrameFlag: false,
    });
 },

 //保存图片
 saveImage: function () {
    var that = this;
    var filePath = that.data.shengchengUrl;

    wx.saveImageToPhotosAlbum({
       filePath: filePath,
       success: function (res) {
          wx.showToast({
             title: '保存图片成功！',
             icon: 'none',
             duration: 1000,
             mask: true,
          })
       }
    })
 },

   //分享到朋友圈
   generate() {
    wx.showLoading({
       title: '正在生成中',
    })

    var that = this;
    that.setData({
       showCanvasFlag: true,
    })

    var textArr = [];
    for (var i = 0; i < that.data.awards.length; i++) {
       textArr.push(that.data.awards[i]);
    }


    that.makeImageCanvas('shareCanvas', "提肛神器", textArr, that.data.colorArr, that.data.fontArr, that.data.sizeArr, 600, 20, 20, 40, that.data.canvasWidth, that.data.canvasHeight, 120, 400, that.data.eweimaUrl);

    setTimeout(function () {
       wx.canvasToTempFilePath({
          x: 0,
          y: 0,
          width: that.data.canvasWidth,
          height: that.data.canvasHeight,
          canvasId: 'shareCanvas',
          success: function (res) {
             console.log(res.tempFilePath);

             that.setData({
                showCanvasFlag: false,
                saveFrameFlag: true,
                shengchengUrl: res.tempFilePath,
             })

             wx.hideLoading();
          }
       })
    }, 2000)

 },

 
   //画图--画布:canvasName画布ID名，title标题，textArr内容数组，colorArr字体颜色数组，fontArr字体样式数组，sizeArr字体大小数组，num总数量，rowNum一行数量--最大为5，distance同行中词的距离，spacing第二行与第一行隔多少距离，canvasWidth画布宽度，canvasHeight画布高度，midWidth中间宽度，midHeight中间高度，imgUrl二维码图片路径
   makeImageCanvas: function (canvasName, title, textArr, colorArr, fontArr, sizeArr, num, rowNum, distance, spacing, canvasWidth, canvasHeight, midWidth, midHeight, imgUrl) {
    var that = this;

    var contentArr = [];
    for (var a = 0; a < num; a++) {
       var neirong = that.arrayRandomTakeOne(textArr);//内容
       contentArr.push(neirong);
    }
    //console.log(contentArr);

    const ctx = wx.createCanvasContext(canvasName)
    ctx.clearRect(0, 0, canvasWidth, canvasHeight)//清除画布区域内容
    ctx.setFillStyle('white')//填充背景色--白色
    ctx.fillRect(0, 0, canvasWidth, canvasHeight)

    var daxiaoArr = [];
    for (var i = 0; i < contentArr.length; i++) {
       var hang = parseInt(i / rowNum) + 1;//第几行
       var hangDj = i % rowNum;//每行第几
       var yanse = that.arrayRandomTakeOne(colorArr);//颜色
       var ziti = that.arrayRandomTakeOne(fontArr);//字体
       var daxiao = that.arrayRandomTakeOne(sizeArr);//大小
       daxiaoArr.push(daxiao);
       //console.log(yanse, ziti, daxiao);

       var rowStart = 0;//水平起点
       var columnStart = hang * spacing;//竖直起点

       if (hangDj == 0) {
          rowStart = 0;
       }
       else if (hangDj > 0) {
          for (var e = 1; e < hangDj + 1; e++) {
             rowStart = rowStart + contentArr[i - e].length * daxiaoArr[i - e];
          }
          rowStart = rowStart + distance * hangDj;
       }
       //console.log('起点', rowStart);

       ctx.fillStyle = yanse;//字体颜色
       ctx.font = ziti + ' small-caps normal ' + daxiao + 'px Arial';
       ctx.fillText(contentArr[i], rowStart, columnStart)
    }

    ctx.setFillStyle('white')//填充背景色--白色
    ctx.fillRect((canvasWidth - midWidth) / 2, (canvasHeight - midHeight) / 2, midWidth, midHeight)

    var titleArr = [];
    for (var n = 0; n < title.length; n++) {
       titleArr.push(title[n]);
    }
    //console.log(titleArr);

    var titleHeight = midHeight - 10 - midWidth;
    var titleDaxiao = parseInt(titleHeight / title.length);
    //console.log(titleHeight, titleDaxiao);

    titleDaxiao = titleDaxiao > 50 ? 50 : titleDaxiao;

    for (var m = 0; m < titleArr.length; m++) {
       ctx.fillStyle = '#000000';//字体颜色
       ctx.font = 'normal small-caps normal ' + titleDaxiao + 'px Arial';
       ctx.setTextAlign('center')
       ctx.fillText(titleArr[m], canvasWidth / 2, (canvasHeight - midHeight) / 2 + 5 + titleDaxiao * (m + 1))
    }

    ctx.drawImage(imgUrl, (canvasWidth - midWidth) / 2 + 5, canvasHeight - (midWidth + (canvasHeight - midHeight) / 2), midWidth - 10, midWidth - 10)//二维码

    wx.drawCanvas({
       canvasId: canvasName,
       actions: ctx.getActions()
    })
 },

 //数组随机取出一个数
 arrayRandomTakeOne: function (array) {
    var index = Math.floor((Math.random() * array.length + 1) - 1);
    return array[index];
 },

  onLoad:function(){

    
    // 在页面onLoad回调事件中创建插屏广告实例
    if (wx.createInterstitialAd) {
      interstitialAd = wx.createInterstitialAd({
        adUnitId: 'adunit-e2a4de089b4818fb'
      })
      interstitialAd.onLoad(() => {})
      interstitialAd.onError((err) => {})
      interstitialAd.onClose(() => {})
    }
console.log(interstitialAd)
    // 在适合的场景显示插屏广告
    if (interstitialAd) {
      interstitialAd.show().catch((err) => {
        console.error(err)
      })
    }


   var that=this
    var res =  wx.getSystemInfoSync();
    var rate = 750 / res.windowWidth;
    this.setData({
      rate : rate,
      clockHeight : rate * res.windowHeight
    })

    /**
       * 监听音乐播放
       */
      wx.onBackgroundAudioPlay(function() {
        console.log('开始')
       
       
      }),

      /**
       * 监听音乐暂停
       */
      wx.onBackgroundAudioPause(function() {
      console.log('onBackgroundAudioPause')
      }),

      /**
       * 监听音乐停止
       */
      wx.onBackgroundAudioStop(function() {
        console.log('停止')
      
        
            
      })
  },
  bindChange: function (e) {
    const val = e.detail.value
    this.setData({
      time: this.data.times[val[0]],
    })
    timeStr:  this.data.day+':00'
    if(this.data.time < 10){
      let oneDigitTime = this.data.time.substr(1,1)
      this.setData({
        timeLong : oneDigitTime
      })
    }else{
      this.setData({
        timeLong : this.data.time
      })
    }
   
  },
  picker:function(){
    this.setData({
      pickerShow:true
    })
  },
  timer:function(e){
    let _this = this
    this.setData({
      pickerShow:false,
      timeStr:  _this.data.time+':00',
      
    })
  },
  start:function(){
    var that=this
  
    //一天只能提肛三次，超过三次，则无法提肛
    var date = new Date();
    var Y = date.getFullYear() + '-';
    var M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-';
    var DD = (date.getDate() < 10 ? '0' + date.getDate() : date.getDate()) ;
    wx.cloud.callFunction({
      name: 'getopenid',//调用云函数获取用户唯一openid
      complete: res => {
        const openid = res.result.openid
        db.collection('record').where({
          _openid: openid,
          status:1,
          date:Y+M+DD
        }).count()
        .then(res=>{
          if(res.total>=3){
            wx.showToast({
              title: '每日提肛不宜超过三次！',
              icon: 'none',
              duration: 3000
            })
          }else{
            that.setData({
              clockShow :　true,
              mTime : this.data.time*60*1000,
              startShow: false
            })
            that.drawBg()
            that.drawActive()
            that.backmusic(that.data.miaovalue)
          }
        })
      }
    })



    
  },
  drawBg:function () {
    var lineWidth = 4 / this.data.rate; // px
    var ctx =wx.createCanvasContext('progress_bg');
    ctx.setLineWidth(lineWidth);
    ctx.setStrokeStyle('#92938D');
    ctx.setLineCap('round');
    ctx.beginPath();
    ctx.arc(500/this.data.rate/2,500/this.data.rate/2,500/this.data.rate/2- 2* lineWidth,0,2*Math.PI,false);
    ctx.stroke();
    ctx.draw();
  },
  drawActive: function () {
    var _this = this;
    var timer = setInterval(function (){
      // 1.5 3.5
      // 0 2 
      // 300000 100
      // 3000
      // 2 / 3000
      var angle = 1.5 + 2*(_this.data.time*60*1000 - _this.data.mTime)/(_this.data.time*60*1000);
      var currentTime = _this.data.mTime - 100
      _this.setData({
          mTime: currentTime
      });
      if(angle < 3.5) {
  
        if(currentTime % 1000 == 0) {
          var timeStr1 = currentTime / 1000; // s
          var timeStr2 = parseInt(timeStr1 / 60) // m
          var timeStr3 = (timeStr1 - timeStr2 * 60) >= 10 ? (timeStr1 - timeStr2 * 60) : '0' + (timeStr1 - timeStr2 * 60);
          var timeStr2 = timeStr2 >= 10 ? timeStr2:'0'+timeStr2;
          _this.setData({
            timeStr:timeStr2+':'+timeStr3
          })
        }
        var lineWidth =4 / _this.data.rate; // px
        var ctx = wx.createCanvasContext('progress_active');
        ctx.setLineWidth(lineWidth);
        ctx.setStrokeStyle('#FC4A62');
        ctx.setLineCap('round');
        ctx.beginPath();
        ctx.arc(500 / _this.data.rate / 2, 500 / _this.data.rate / 2, 500 / _this.data.rate / 2 - 2 * lineWidth, 1.5 * Math.PI, angle * Math.PI, false);
        ctx.stroke();
        ctx.draw();

      } else {   
        wx.pauseBackgroundAudio({
          success: function(res){
            console.log('背景音乐暂停2')
            that.setData({
              biaoji:0
            })
          }
        })
   
        _this.setData({
           'tomatoRecord.uid':wx.getStorageSync('userinfo').id,
           'tomatoRecord.timeLong' : _this.data.timeLong
        })
        // wx.request({
        //   url: TomatoUrl,
        //   data: _this.data.tomatoRecord,
        //   method: 'POST', 
        // })
        _this.setData({
          timeStr:'00:00',
          startShow:true,
          clockShow : false
        })
        clearInterval(timer);
        //正常打卡完成
        _this.addRanking(1)
      }
    },100);
    _this.setData({
      timer:timer
    })
  },
  
  onShow:function(){
    var that=this
    wx.setKeepScreenOn({
      keepScreenOn: true
    })
    wx.getStorage({
      key: 'user',
      success: function(res) {

        that.setData({
          isLogin: 1,
          nickName:res.data.nickName,
          avatarUrl:res.data.avatarUrl
        })
      }, fail () {
      
      }
    })
  },
  cancle:function(){
    var that=this
    wx.showModal({
      title: '提示',
      content: '如果您提前终止，则不计入有效提肛？',
      success: function (sm) {
        if (sm.confirm) {
            // 用户点击了确定 可以调用删除方法了
            wx.pauseBackgroundAudio({
              success: function(res){
                console.log('背景音乐暂停1')
                that.setData({
                  biaoji:0
                })
              }
            })
            that.setData({
              clockShow : false,
              startShow: true
            })
            clearInterval(that.data.timer)
            that.addRanking(0)
          } else if (sm.cancel) {
            console.log('用户点击取消')
          }
        }
      })
    
  },

  //用户登录授权
  getUserProfile() {
    var that=this
   wx.getUserProfile({
     desc: '用于完善个人资料', // 声明获取用户个人信息后的用途，后续会展示在弹窗中，请谨慎填写
     success: (res) => {
       console.log(res)
      wx.setStorage({
        key: 'user',
        data: res.userInfo,
      })
      that.setData({
        isLogin: 1,
        nickName:res.userInfo.nickName,
        avatarUrl:res.userInfo.avatarUrl
      })
      that.start()
     }
   })
 },
   //写入数据到集合ranking和 record当中
  addRanking(status){
    var that=this
    var date = new Date();
    var Y = date.getFullYear() + '-';
    var M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-';
    var D = (date.getDate() < 10 ? '0' + date.getDate() : date.getDate()) + '  ';
    var DD = (date.getDate() < 10 ? '0' + date.getDate() : date.getDate()) ;
    var h = (date.getHours() < 10 ? '0' + date.getHours() : date.getHours()) + ':';
    var m = (date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes()) + ':';
    var s = (date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds());
    //重置收放
    that.setData({
      biaoji:0
    })
    //2、查询状态为是否存在打卡记录
    wx.cloud.callFunction({
      name: 'getopenid',//调用云函数获取用户唯一openid
      complete: res => {
        const openid = res.result.openid
        db.collection('ranking').where({
          _openid: openid,
        })
        .get({
          success: function(res) {
           
            
            if(res.data.length==0&&Object.keys(res.data).length === 0){//如果原先没有记录
              var count=0
              if(status==1){//有效打卡
                count=1
              }
              db.collection('ranking').add({ //插入记录ranking
                data: {
                  create_time: Y+M+D+h+m+s,
                  date:Y+M+DD,
                  nickName:that.data.nickName,
                  avatarUrl:that.data.avatarUrl,
                  count:count
                }
              }).then(res => {          
                      db.collection('record').add({
                        data: {
                          create_time: Y+M+D+h+m+s,
                          date:Y+M+DD,
                          status:status,
                          nickName:that.data.nickName,
                          avatarUrl:that.data.avatarUrl
                        }
                      }).then(res => {
                        if(status==1){//有效打卡
                          // wx.showToast({
                          //   title: '提肛成功！',
                          //   icon: 'success',
                          //   duration: 2000
                          // })
                          that.generate()
                        }else{
                          that.generate()
                        }
                        
                      }).catch(console.error)
              }).catch(console.error)
            }else if(res.data.length>0&&Object.keys(res.data).length > 0){//如果存在记录
              if(status==0){//无效打卡
                db.collection('record').add({
                  data: {
                    create_time: Y+M+D+h+m+s,
                    date:Y+M+DD,
                    status:status,
                    nickName:that.data.nickName,
                    avatarUrl:that.data.avatarUrl
                  }
                }).then(res => {
                  that.generate()
                }).catch(console.error)
              }else{//有效打卡
                db.collection('ranking').where({
                  _openid: openid,
                }).update({ //更新记录ranking
                  data: {
                    create_time: Y+M+D+h+m+s,
                    date:Y+M+DD,
                    count:res.data[0].count+1
                  }
                }).then(res => {  
                      db.collection('record').add({
                        data: {
                          create_time: Y+M+D+h+m+s,
                          date:Y+M+DD,
                          status:status,
                          nickName:that.data.nickName,
                          avatarUrl:that.data.avatarUrl
                        }
                      }).then(res => {
                        // wx.showToast({
                        //   title: '提肛成功！',
                        //   icon: 'success',
                        //   duration: 2000
                        // })
                        that.generate()
                      }).catch(console.error)
                }).catch(console.error)
              }
              
            }
          }
        })
      }
    })

  },

  toTomatoData:function(){
    wx.navigateTo({
      url: '/pages/tomato/tomatoRecord/tomatoRecord',
    })
  },
  selectBgMusic:function(){
    let _this = this
    wx.showActionSheet({
      itemList: ['静音','森林', '夏夜','春雨','海浪'],
      success (res) {
        if( res.tapIndex === 0){
          _this.setData({
            sound : false
          })
          wx.pauseBackgroundAudio({
            success: function(res){
              console.log('背景音乐暂停0')
              that.setData({
                biaoji:0
              })
            }
          })
        }else{
          _this.setData({
            sound : true
          })
          _this.backmusic(res.tapIndex)
        }
        console.log(res.tapIndex)
      },
      fail (res) {
        console.log(res.errMsg)
      }
    })
  },
  musicStart(e){
    this.backmusic(Number(e.currentTarget.dataset.id))
    console.log(9999)
  },
  gobackmusic(e){
    if(this.data.startShow){
      this.setData({
        miaovalue:e.currentTarget.dataset.id
      })
      return
    }
    wx.getBackgroundAudioManager().stop();
    this.setData({
      miaovalue:e.currentTarget.dataset.id
    })
    this.backmusic(e.currentTarget.dataset.id)
 
  },
  backmusic: function (index) {
      var that=this
       let bgm = ''
       if(index == 1){
         bgm = '1s'
       }
       if(index == 2){
        bgm = '3s'
       }
       if(index == 3){
        bgm = '5s'
       }
     
       player();
  
       function player() {
       
         back.title = "bgm";   // 必须要有一个title
         back.src = "cloud://cloud1-9g6sqrsoc25b6bd5.636c-cloud1-9g6sqrsoc25b6bd5-1306709779/shoufang3.mp3";  
         back.onEnded(() => {    
           player();  // 音乐循环播放
         })
         if(index==1){//1s
        
          that.setData({
            biaoji:1
          })
        
          setTimeout(() => {
            that.setData({
              biaoji:2
            })
          }, 1000);
          setTimeout(() => {
            that.setData({
              biaoji:3
            })
          }, 2000);
         }
         if(index==2){//3s
          that.setData({
            biaoji:1
          })
        
          setTimeout(() => {
            that.setData({
              biaoji:2
            })
          }, 1000);
          setTimeout(() => {
            that.setData({
              biaoji:3
            })
          }, 3000);
         }
         if(index==3){//5s
          that.setData({
            biaoji:1
          })
        
          setTimeout(() => {
            that.setData({
              biaoji:2
            })
          }, 1000);
          setTimeout(() => {
            that.setData({
              biaoji:3
            })
          }, 5000);
         }
      }
   }, 
    /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})

